﻿using Microsoft.AspNetCore.Mvc;
using Redis实战.Models;
using Redis实战.Services;

namespace Redis实战.Controllers
{
    
        /// <summary>
        /// 用户API控制器（集成Redis缓存）
        /// </summary>
        [ApiController]
        [Route("api/[controller]")]
        public class UserController : ControllerBase
        {
            private readonly UserService _userService;
            private readonly ILogger<UserController> _logger;

            /// <summary>
            /// 构造函数（依赖注入）
            /// </summary>
            public UserController(UserService userService, ILogger<UserController> logger)
            {
                _userService = userService;
                _logger = logger;
            }

            /// <summary>
            /// 获取用户（优先从Redis缓存获取）
            /// </summary>
            /// <param name="id">用户ID</param>
            /// <returns>用户信息</returns>
            [HttpGet("{id}")]
            [ProducesResponseType(StatusCodes.Status200OK)]
            [ProducesResponseType(StatusCodes.Status404NotFound)]
            public async Task<ActionResult<User>> GetUser(int id)
            {
                _logger.LogInformation($"查询用户 ID: {id}");
                var user = await _userService.GetUserByIdAsync(id);

                if (user == null)
                {
                    _logger.LogWarning($"用户 ID: {id} 未找到");
                    return NotFound($"用户 ID: {id} 不存在");
                }

                return Ok(user);
            }

            /// <summary>
            /// 创建用户（同时写入缓存）
            /// </summary>
            /// <param name="user">用户信息</param>
            /// <returns>创建的用户</returns>
            [HttpPost]
            [ProducesResponseType(StatusCodes.Status201Created)]
            [ProducesResponseType(StatusCodes.Status400BadRequest)]
            public async Task<ActionResult<User>> CreateUser(User user)
            {
                if (user == null || string.IsNullOrEmpty(user.Name))
                {
                    return BadRequest("用户信息无效");
                }

                // 1. 保存到数据库（实际项目中实现IUserRepository的Create方法）
                await _userService.CreateUserAsync(user);

                // 2. 同步到缓存
                var cacheKey = $"User:{user.Id}";
                await _userService.CreateUserAsync(user);

                _logger.LogInformation($"创建用户成功 ID: {user.Id}");
                return CreatedAtAction(nameof(GetUser), new { id = user.Id }, user);
            }

            /// <summary>
            /// 更新用户（同时更新缓存）
            /// </summary>
            /// <param name="id">用户ID</param>
            /// <param name="user">更新的用户信息</param>
            /// <returns>操作结果</returns>
            [HttpPut("{id}")]
            [ProducesResponseType(StatusCodes.Status204NoContent)]
            [ProducesResponseType(StatusCodes.Status400BadRequest)]
            [ProducesResponseType(StatusCodes.Status404NotFound)]
            public async Task<IActionResult> UpdateUser(int id, User user)
            {
                if (id != user.Id)
                {
                    return BadRequest("ID不匹配");
                }

                var existingUser = await _userService.GetUserByIdAsync(id);
                if (existingUser == null)
                {
                    return NotFound($"用户 ID: {id} 不存在");
                }

                // 1. 更新数据库
                await _userService.UpdateUserAsync(user);

                // 2. 更新缓存（自动覆盖旧值）
                _logger.LogInformation($"更新用户缓存 ID: {id}");

                return NoContent();
            }

            /// <summary>
            /// 删除用户（同时删除缓存）
            /// </summary>
            /// <param name="id">用户ID</param>
            /// <returns>操作结果</returns>
            [HttpDelete("{id}")]
            [ProducesResponseType(StatusCodes.Status204NoContent)]
            [ProducesResponseType(StatusCodes.Status404NotFound)]
            public async Task<IActionResult> DeleteUser(int id)
            {
                var user = await _userService.GetUserByIdAsync(id);
                if (user == null)
                {
                    return NotFound($"用户 ID: {id} 不存在");
                }

                // 1. 从数据库删除（实际项目中实现IUserRepository的Delete方法）
                await _userService.DeleteUserAsync(id);

                // 2. 从缓存删除
                await _userService.RemoveUserCacheAsync(id);

                _logger.LogInformation($"删除用户及缓存 ID: {id}");
                return NoContent();
            }
        }
    
}
